<%@ include file="/WEB-INF/jsp/common/include.jsp" %><%@ page
pageEncoding="UTF-8"%><%@ page
import="java.util.List"%><%@ page
import="java.util.ArrayList"%><%@ page
import="com.google.appengine.api.datastore.Key"%><%@ page
import="com.bac.rentmap.ad.flat.search.SearchParameters"%><%@ page
import="com.bac.rentmap.ad.flat.FlatAd"%><%@ page
import="com.google.appengine.api.users.UserService"%><%@ page
import="com.google.appengine.api.users.UserServiceFactory"%><%@ page 
import="com.bac.rentmap.map.thumbnail.Point"%><%@ taglib
uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %><%@ taglib
prefix="app" uri="AppTags" %><tiles:insertDefinition name="searchLayout.tiles">
  <tiles:putAttribute name="pageMessageKey">search.list</tiles:putAttribute>
  <tiles:putAttribute name="adListTab" cascade="true">selected</tiles:putAttribute>
  <tiles:putAttribute name="searchResult" cascade="true">
  <script>
    var flatAds = {};
    $("#price-range").slider({
      range: true,
      min: minPrice - step,
      max: maxPrice + step,
      values: [curMinPrice, curMaxPrice],
      step: step,
      slide: function(event, ui) {
        var newMinPrice = ui.values[0];
        if(newMinPrice < minPrice){
          newMinPrice = '';
        }
        $("#minPrice").val(newMinPrice);
        var newMaxPrice = ui.values[1];
        if(newMaxPrice > maxPrice){
          newMaxPrice = '';
        }
        $("#maxPrice").val(newMaxPrice);
        updatePriceRangeLabel(ui.values[0], ui.values[1])
      }
    });
    $(function() {
      adjustLayoutToWindow();
      $(".scrollable").scrollable();
      $.superbox.settings = {
              loadTxt:'Загрузка...',
              closeTxt: 'Закрыть',
              prevTxt: 'Предыдущая',
              nextTxt: 'Следующая'
      };
      $.superbox();
      $(window).scroll(function(e){
        var newFlatAds = {};
        for(var flatAd in flatAds){
          var flatAdElement = document.getElementById('flatAd' + flatAd);
          if(isElementInViewport(flatAdElement)){
            $.post('<app:slaveServerUrl />/ad/user/view/statistics/inc.do?flatAdId=' + flatAd);
          }
          else{
            newFlatAds[flatAd] = true;
          }
        }
        flatAds = newFlatAds;
      });
    });
    $( window ).resize(function() {
      adjustLayoutToWindow();
    });
    function adjustLayoutToWindow(){
        if((window.innerWidth || document.documentElement.clientWidth) < 1024){
            $('#search').css('position', 'absolute');
        }
        else{
            $('#search').css('position', 'fixed');
        }
    }
    function isElementInViewport (el) {
      var rect = el.getBoundingClientRect();
      return (
          rect.top >= 0 &&
          rect.left >= 0 &&
          rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
          rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
      );
    }
    if(readCookie('showUserReviewThankYou') == 'true'){
      alert('Спасибо за отзыв. Ваш отзыв будет рассмотрен в ближайшее время.');
    }
    eraseCookie('showUserReviewThankYou');
  </script>
  <script type="text/javascript" src="<app:slaveServerUrl />/js/jquery/plugins/superbox/jquery.superbox.js"></script>
  <div id="list">
    <%
      UserService userService = UserServiceFactory.getUserService();
      int currentPage = ((SearchParameters)request.getAttribute("searchParameters")).getPage();
      pageContext.setAttribute("currentPage", currentPage);
    %>
    <!--List item-->
      <c:forEach var="flatAd1" items="${flatAds}" varStatus="status">
        <c:set var="flatAd" value="${flatAd1}" scope="request"/>
        <c:if test="${not empty flatAd}">
          <c:set var="normalizedRating" value="${normalizedRatings[status.count - 1]}" scope="request"/>
          <c:if test="${status.count == 6}">
<div class="box white-box">
<c:choose>
  <c:when test="${currentPage < 0}">
    <script type="text/javascript">
    yandex_partner_id = 91614;
    yandex_site_bg_color = 'FFFFFF';
    yandex_site_charset = 'utf-8';
    yandex_ad_format = 'direct';
    yandex_font_size = 1;
    yandex_direct_type = 'horizontal';
    yandex_direct_limit = 1;
    yandex_direct_title_font_size = 3;
    yandex_direct_header_bg_color = 'FEEAC7';
    yandex_direct_title_color = '0000CC';
    yandex_direct_url_color = '006600';
    yandex_direct_text_color = '000000';
    yandex_direct_hover_color = '0066FF';
    yandex_direct_favicon = true;
    document.write('<sc'+'ript type="text/javascript" src="http://an.yandex.ru/system/context.js"></sc'+'ript>');
    </script>
    <br/>
  </c:when>
  <c:otherwise>
    <a href="http://bling.by/?partner=2"><img src="<app:slaveServerUrl />/image/external/bling.jpg" style="border-radius: 4px; margin-bottom: 10px" title="bling.by" alt="bling.by"/></a>
  </c:otherwise>
</c:choose>
  </div>
          </c:if>
        <c:set var="thumbnailPoint" value="${thumbnailPoints[status.count - 1]}"/>
        <c:if test="${not empty flatAd.secureId}">
          <script>
            flatAds["<c:out value='${flatAd.id}'/>"] = true;
          </script>
        </c:if>
        <!--List item-->
        <tiles:insertDefinition name="adContent.tiles">
          <tiles:putAttribute name="images">
<%
  FlatAd flatAd = (FlatAd)request.getAttribute("flatAd");
  List flatImages = new ArrayList();
  if(flatAd.getExternal()){
    flatImages = flatAd.getExternalImages();
  }
  else{
    for(Key flatImageKey : flatAd.getFlatImages()){
      flatImages.add(flatImageKey.getId());
    }
  }
  pageContext.setAttribute("flatImages", flatImages);
  Point thumbnailPoint = (Point)pageContext.getAttribute("thumbnailPoint");
  boolean mapLocationDefined = thumbnailPoint != null;
  pageContext.setAttribute("mapLocationDefined", mapLocationDefined);
  int locationImageCount = mapLocationDefined ? 1 : 0;
  if(mapLocationDefined){
    pageContext.setAttribute("locationImageX", thumbnailPoint.getX());
    pageContext.setAttribute("locationImageY", thumbnailPoint.getY());
  }
%>
<c:if test="${mapLocationDefined || not empty flatImages}">
  <%

    final int imageCountPerSection = 4;
    int imageCount = flatImages.size() + locationImageCount;
    int sectionCount = imageCount / imageCountPerSection;;
    if(imageCount % imageCountPerSection != 0){
      sectionCount++;
    }
  %>
  <a class='prev browse left <%= sectionCount > 1 ? "" : "disabled" %>'></a>
  <div class="scrollable">
    <div class="items">
      <%
        for(int i = 0; i < sectionCount; i++){
      %>
        <div class="section">
          <%
            for(int j = 0; j < imageCountPerSection; j++){
              int ind = i * imageCountPerSection + j;
              if(ind < locationImageCount){
          %><div class="wraptocenter"><span></span>
            <a href="#" data-href="#osm-${flatAd.city}-${flatAd.agent ? 'agent' : 'owner'}-${flatAd.lat}-${flatAd.lon}-${flatAd.street}"
               rel="superbox[gallery][flatGallery${flatAd.id}]">
              <img src="/image/city/${flatAd.city}-small.png" />
              <img src="/image/map/${flatAd.agent ? 'agent' : 'owner'}-map.png" class="imageGalleryMarker" style="left : ${locationImageX - 10}px; top : ${110 - locationImageY - 12}px"/>
            </a>
            </div>
          <%
              }
              else if(ind < imageCount){
                pageContext.setAttribute("flatImageId", flatImages.get(ind - locationImageCount));
          %><div class="wraptocenter"><span></span>
            <a href="#" data-href="${flatImageId}"
               rel="superbox[gallery][flatGallery${flatAd.id}]">
              <c:choose>
                <c:when test="${flatAd.external}">
                  <img src="${flatImageId}" />
                </c:when>
                <c:otherwise>
                  <img src="/ad/image/serve/thumbnail.do?flatImageId=${flatImageId}" />
                </c:otherwise>
              </c:choose>
            </a>
            </div>
          <%
              }
            }
          %>
        </div>
      <%
        }
      %>
    </div>
  </div>
  <a class='next browse right <%= sectionCount > 1 ? "" : "disabled" %>'></a>
  <div style="clear:both"></div>
</c:if>
            </tiles:putAttribute>
          </tiles:insertDefinition>
        </c:if>
      </c:forEach>
    </div>
    <!--Paging-->
    <div class="paging white-box" style="min-height: 52px">
      <ul>
        <tiles:insertTemplate template="prevButton.jsp"/>
        <tiles:insertTemplate template="nextButton.jsp"/>
      </ul>
      <ul class="num">
          <%
            int startIndex = Math.max(0, currentPage - 9);
            for(int i = startIndex; i < currentPage; i++){
          %>
            <c:url value="/ad/search/list.do" var="pageLink">
              <c:param name="minPrice" value="${searchParameters.minPrice}"/>
              <c:param name="maxPrice" value="${searchParameters.maxPrice}"/>
              <c:param name="room" value="${searchParameters.room}"/>
              <c:param name="page"><%= i %></c:param>
              <c:if test="${loggedIn}">
                <c:param name="loggedIn" value="${loggedIn}"/>
              </c:if>
            </c:url>
            <li><a href="${pageLink}"><%= i + 1 %></a></li>
          <%
            }
          %>
          <c:if test="${searchParameters.page gt 0}">
            <li><b>${searchParameters.page + 1}</b></li>
          </c:if>
      </ul>
    </div>
    <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
    <script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
  </tiles:putAttribute>
</tiles:insertDefinition>